package com.example.hdx.service;

import com.example.hdx.DOT.loginrDTO;
import com.example.hdx.entity.User;
import com.example.hdx.mapper.UserMapper;
import com.example.hdx.util.FwResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.hdx.DOT.loginDTO;
import com.example.hdx.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;



@Service
public class UserService {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;
//    public FwResult<User> login(String username, String password) {
//        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        wrapper.eq("username", username);
//
//        User user = userMapper.selectOne(wrapper);
//        String token = JwtUtil.createToken();
//
//        if (user == null || !user.getPassword().equals(password)) {
//            return FwResult.failedMsg("用户名或密码错误");
//        }
//
//        return FwResult.ok(user);
//    }
public FwResult<loginrDTO> login(String username,String password) {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("username", username);

    User user = userMapper.selectOne(wrapper);

    if (user == null || !user.getPassword().equals(password)) {
        return FwResult.failedMsg("用户名或密码错误");
    }

    // 生成 Token
    String token = JwtUtil.createToken(user.getId());

    // 构建返回值对象
    loginrDTO loginrDTO = new loginrDTO();
    loginrDTO.setId(user.getId());
    loginrDTO.setUsername(user.getUsername());
    loginrDTO.setToken(token);

    return FwResult.ok(loginrDTO);
}



    public FwResult<Void> register(User user) {
        // 检查用户名是否已存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());

        if (userMapper.selectOne(wrapper) != null) {
            return FwResult.failedMsg("用户名已存在");
        }

        // 插入新用户
        int rows = userMapper.insert(user);
        if (rows <= 0) {
            return FwResult.failed();
        }

        return FwResult.ok();
    }
}